﻿using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Timers;
using System.Windows.Forms;
namespace Template
{
    public partial class Form1 : Form
    {

        private static System.Timers.Timer _timer;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;//经典解决“线程间操作无效: 从不是创建控件的线程访问它”
            // 创建一个定时器对象，并设置其时间间隔为1000毫秒（即1秒）
            _timer = new System.Timers.Timer(1000);        
            //// 绑定回调函数到定时器的Elapsed事件
            _timer.Elapsed += TimerElapsed;
           
            //// 设置定时器是否重复触发（true表示重复触发，false表示只触发一次）
            _timer.AutoReset = true;           
        }
    

        uint i = 0;
        // 定时器回调函数（上面已经定义过，这里为了完整性再次展示）
        private void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            i++;
            AppendLogColorful("hhff"+i.ToString());
            //Console.WriteLine("定时器触发了！当前时间是：" + DateTime.Now.ToString("HH:mm:ss"));
        }



        /// <summary>
        /// 将byte字符串转化成字符串
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        static string ByteArrayToString(byte[] hex)
        {
            StringBuilder resulet = new StringBuilder(hex.Length);
            foreach (byte b in hex)
            {
                resulet.Append(b.ToString("X2"));
            }
            return resulet.ToString();
        }

        /// <summary>
        /// 将字符串转化成byte数组
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        static byte[] StringToByteArray(string hex)
        {

            hex = hex.Replace(" ", "");

            if (hex.Length % 2 != 0)
                throw new ArgumentException(hex + " is not a valid hex string!");
            byte[] ret = new byte[hex.Length / 2];
            for (int i = 0; i < ret.Length; i++)
            {
                ret[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            return ret;
        }
        /// <summary>
        /// 打印调试数据
        /// </summary>
        /// <param name="rtBox"></param>
        /// <param name="text"></param>
        /// <param name="color"></param>
        /// <param name="addNewLine"></param>
        private void AppendLogColorful(RichTextBox rtBox, string text, Color color, bool addNewLine = true)
        {
            this.Invoke(new Action(() =>
            {
                rtBox.SelectionStart = rtBox.TextLength;
                rtBox.SelectionLength = 0;
                rtBox.SelectionColor = color;
                rtBox.AppendText(text);
                rtBox.SelectionColor = rtBox.ForeColor;
                if (addNewLine)
                {
                    rtBox.AppendText("\r\n");
                    rtBox.SelectionStart = rtBox.Text.Length;

                    rtBox.ScrollToCaret();
                }
            }));
        }
        /// <summary>
        /// Log调试显示界面
        /// </summary>
        /// <param name="rtBox"></param>
        /// <param name="text"></param>
        /// <param name="color"></param>
        private void AppendLogColorful(string text)
        {
            if (richTextBox1.Text.Length > 10000)
                richTextBox1.Text = "";
            // textBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + "  " + text + Environment.NewLine);
            richTextBox1.AppendText(DateTime.Now.ToString("HH:mm:sss") + "  " + text + Environment.NewLine);

        }


        #region CRC16校验
        /// <summary>
        /// CRC16校验
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        ///注意，输入字符串没有将CRC校验码算进去。

        public int CRC_GetModbus16(byte[] Data, int length)  //MODBUS CRC计算
        {
            int CRC0 = 0xFFFF, mid = 0;
            for (int i = length, Data_index = 0; i > 0; i--)
            {
                CRC0 = Data[Data_index] ^ CRC0;//把数据帧中的第一个字节的8位与CRC寄存器中的低字节进行异或运算，结果存回CRC寄存器
                for (int times = 0; times < 8; times++)
                {
                    mid = CRC0;
                    CRC0 = CRC0 >> 1;
                    if ((mid & 0x0001) == 0x0001)
                    { CRC0 = CRC0 ^ 0xA001; }
                }
                Data_index++;
            }
            return CRC0;
        }
        #endregion

   
        private void button2_Click(object sender, EventArgs e)
        {
           // AppendLogColorful(richTextBox1, "启动测试引擎...", Color.Green);
            AppendLogColorful("启动测试引擎");
            // _timer.Enabled = true;
            ReadUdisk();
        }



         private void   ReadUdisk()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();//新建一个对话框
            openFileDialog.Filter = "文本文件|*.txt"; // 设置只选择txt文件
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                try
                {
                    string content = File.ReadAllText(filePath);
                    AppendLogColorful(content);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("读取文件时出错：" + ex.Message);
                }
            }


        }


    }
   }

